import numpy as np


def PathLength(D, Chrom):
    """
    计算各个体的路径长度
    :param D: 两两城市之间的距离
    :param Chrom: 个体的轨迹
    :return: 总路径长度
    """
    if len(np.shape(Chrom)) > 1:
        NIND = np.shape(Chrom)[0]
    elif len(np.shape(Chrom)) == 1:
        NIND = 1
    else:
        return np.zeros((0, 1))
    result = np.zeros((NIND, 1))
    for i in range(NIND):
        if NIND >1:
            p = np.append(Chrom[i, :], Chrom[i, 0])
        else:
            p = np.append(Chrom[i:], Chrom[0])
        p = [int(i-1) for i in p]
        i1 = p[:-1]
        i2 = p[1:]
        lst = [D[i1[i]][i2[i]] for i in range(len(i1))]
        result[i] = np.sum(lst)
    return result
